package cn.cuilan.config;

import cn.cuilan.utils.NetworkUtils;
import cn.cuilan.utils.Results;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登出成功处理器
 *
 * @author zhang.yan
 */
public class LogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        if (authentication != null) {
            logger.info(String.format("用户：[%s] 登出系统，IP：[%s]",
                    authentication.getName(),
                    NetworkUtils.getIpAddress(request)));
        }

        // 设置响应状态为 200
        response.setStatus(HttpStatus.OK.value());
        // 设置响应文本类型为 application/json
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 设置响应体
        JSONObject resultJson = new JSONObject(Results.success().data("登出成功"));
        // 开流写出数据
        PrintWriter out = response.getWriter();
        out.write(resultJson.toString());
        out.flush();
        out.close();
    }
}
